<template>
  <div>
    <!-- 搜索和筛选区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input 
        clearable 
        style="width: 260px; margin-right: 5px" 
        v-model="searchParams.keyword" 
        placeholder="搜索任务标题或描述" 
        :prefix-icon="Search"
      />
      <el-select 
        v-model="searchParams.taskType" 
        clearable 
        style="width: 150px; margin-right: 5px" 
        placeholder="任务类型"
      >
        <el-option label="全部类型" value="" />
        <el-option label="快递代拿" value="express" />
        <el-option label="外卖代拿" value="takeout" />
        <el-option label="药品代购" value="medicine" />
        <el-option label="跑腿服务" value="errand" />
        <el-option label="其他服务" value="other" />
      </el-select>
      <el-select 
        v-model="searchParams.status" 
        clearable 
        style="width: 150px; margin-right: 5px" 
        placeholder="任务状态"
      >
        <el-option label="全部状态" value="" />
        <el-option label="待接单" value="pending" />
        <el-option label="进行中" value="in_progress" />
        <el-option label="已完成" value="completed" />
      </el-select>
      <el-button type="primary" icon="Search" @click="searchTasks">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <!-- 任务列表 -->
    <div class="task-list">
      <el-empty v-if="taskList.length === 0" description="暂无任务" />
      
      <el-card v-for="task in taskList" :key="task.id" class="task-card" shadow="hover">
        <div class="task-header">
          <div class="task-title">
            <el-tag :type="getTaskTypeTag(task.taskType)" effect="plain" size="small">{{ getTaskTypeName(task.taskType) }}</el-tag>
            <span class="title-text">{{ task.title }}</span>
          </div>
          <div class="task-reward">￥{{ task.reward }}</div>
        </div>
        
        <div class="task-content">
          <div class="task-description">{{ task.description }}</div>
          
          <div class="task-details">
            <div class="detail-item">
              <el-icon><Location /></el-icon>
              <span>取件: {{ task.pickupLocation }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Position /></el-icon>
              <span>送达: {{ task.deliveryLocation }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Timer /></el-icon>
              <span>截止时间: {{ formatDate(task.deadline) }}</span>
            </div>
            <div class="detail-item">
              <el-icon><User /></el-icon>
              <span>发布者: {{ task.publisher }}</span>
            </div>
          </div>
        </div>
        
        <div class="task-footer">
          <el-tag :type="getStatusTag(task.status)" effect="dark" size="small">{{ getStatusName(task.status) }}</el-tag>
          <div class="task-actions">
            <el-button 
              v-if="task.status === 'pending'" 
              type="primary" 
              size="small" 
              @click="takeTask(task.id)"
            >接单</el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="viewTaskDetail(task.id)"
            >查看详情</el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 分页 -->
    <div class="card" style="margin-top: 10px">
      <el-pagination
        v-model:current-page="pageParams.pageNum"
        v-model:page-size="pageParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageParams.total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>
    
    <!-- 任务详情对话框 -->
    <el-dialog v-model="taskDetailVisible" title="任务详情" width="600px">
      <div v-if="currentTask" class="task-detail-dialog">
        <div class="detail-header">
          <h3>{{ currentTask.title }}</h3>
          <el-tag :type="getTaskTypeTag(currentTask.taskType)" effect="plain">{{ getTaskTypeName(currentTask.taskType) }}</el-tag>
        </div>
        
        <div class="detail-section">
          <h4>任务描述</h4>
          <p>{{ currentTask.description }}</p>
        </div>
        
        <div class="detail-section">
          <h4>任务信息</h4>
          <div class="detail-item">
            <span class="item-label">报酬:</span>
            <span class="item-value">￥{{ currentTask.reward }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">取件地点:</span>
            <span class="item-value">{{ currentTask.pickupLocation }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">送达地点:</span>
            <span class="item-value">{{ currentTask.deliveryLocation }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">截止时间:</span>
            <span class="item-value">{{ formatDate(currentTask.deadline) }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">发布时间:</span>
            <span class="item-value">{{ formatDate(currentTask.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">发布者:</span>
            <span class="item-value">{{ currentTask.publisher }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">联系方式:</span>
            <span class="item-value">{{ currentTask.contactInfo }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">状态:</span>
            <span class="item-value">
              <el-tag :type="getStatusTag(currentTask.status)" effect="dark" size="small">{{ getStatusName(currentTask.status) }}</el-tag>
            </span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskDetailVisible = false">关闭</el-button>
          <el-button 
            v-if="currentTask && currentTask.status === 'pending'" 
            type="primary" 
            @click="takeTaskAndClose(currentTask.id)"
          >接单</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { Search, Location, Position, Timer, User } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';

// 搜索参数
const searchParams = reactive({
  keyword: '',
  taskType: '',
  status: ''
});

// 分页参数
const pageParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 任务列表
const taskList = ref([]);

// 当前查看的任务
const currentTask = ref(null);
const taskDetailVisible = ref(false);

// 获取任务列表
const fetchTasks = () => {
  request.get('/task/list', {
    params: {
      ...searchParams,
      pageNum: pageParams.pageNum,
      pageSize: pageParams.pageSize
    }
  }).then(res => {
    if (res.code === '200') {
      // 如果有关键词，进行本地模糊搜索
      if (searchParams.keyword) {
        const keyword = searchParams.keyword.toLowerCase();
        const filteredList = res.data.list.filter(task => 
          task.title.toLowerCase().includes(keyword) || 
          task.description.toLowerCase().includes(keyword)
        );
        taskList.value = filteredList;
        pageParams.total = filteredList.length;
      } else {
        taskList.value = res.data.list;
        pageParams.total = res.data.total;
      }
    } else {
      ElMessage.error(res.msg || '获取任务列表失败');
    }
  }).catch(err => {
    console.error('获取任务列表失败:', err);
    ElMessage.error('获取任务列表失败，请稍后重试');
  });
};

// 搜索任务
const searchTasks = () => {
  pageParams.pageNum = 1; // 重置页码
  fetchTasks();
};

// 监听搜索关键词变化
watch(() => searchParams.keyword, (newVal) => {
  if (newVal) {
    searchTasks();
  }
});

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = '';
  searchParams.taskType = '';
  searchParams.status = '';
  searchTasks();
};

// 处理页码变化
const handlePageChange = (page) => {
  pageParams.pageNum = page;
  fetchTasks();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageParams.pageSize = size;
  pageParams.pageNum = 1; // 重置页码
  fetchTasks();
};

// 接单
const takeTask = (taskId) => {
  ElMessageBox.confirm('确定要接此任务吗？接单后请及时与发布者联系。', '接单确认', {
    confirmButtonText: '确定接单',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 这里是模拟接单成功，实际项目中需要连接后端API
    ElMessage.success('接单成功！请及时与发布者联系');
    // 更新任务状态
    const task = taskList.value.find(t => t.id === taskId);
    if (task) {
      task.status = 'in_progress';
    }
    
    // 实际API调用示例

    request.post('/task/take', { taskId }).then(res => {
      if (res.code === '200') {
        ElMessage.success('接单成功！请及时与发布者联系');
        fetchTasks(); // 刷新任务列表
      } else {
        ElMessage.error(res.msg || '接单失败');
      }
    }).catch(err => {
      console.error('接单失败:', err);
      ElMessage.error('接单失败，请稍后重试');
    });

  }).catch(() => {
    // 用户取消接单
  });
};

// 在对话框中接单并关闭
const takeTaskAndClose = (taskId) => {
  takeTask(taskId);
  taskDetailVisible.value = false;
};

// 查看任务详情
const viewTaskDetail = (taskId) => {
  // 查找任务
  const task = taskList.value.find(t => t.id === taskId);
  if (task) {
    currentTask.value = task;
    taskDetailVisible.value = true;
  }
  
  // 实际API调用示例

  request.get('/task/detail', {
    params: { taskId }
  }).then(res => {
    if (res.code === '200') {
      currentTask.value = res.data;
      taskDetailVisible.value = true;
    } else {
      ElMessage.error(res.msg || '获取任务详情失败');
    }
  }).catch(err => {
    console.error('获取任务详情失败:', err);
    ElMessage.error('获取任务详情失败，请稍后重试');
  });

};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
};

// 获取任务类型名称
const getTaskTypeName = (type) => {
  const typeMap = {
    'express': '快递代拿',
    'takeout': '外卖代拿',
    'medicine': '药品代购',
    'errand': '跑腿服务',
    'other': '其他服务'
  };
  return typeMap[type] || '未知类型';
};

// 获取任务类型对应的标签类型
const getTaskTypeTag = (type) => {
  const tagMap = {
    'express': 'primary',
    'takeout': 'success',
    'medicine': 'warning',
    'errand': 'info',
    'other': ''
  };
  return tagMap[type] || '';
};

// 获取任务状态名称
const getStatusName = (status) => {
  const statusMap = {
    'pending': '待接单',
    'in_progress': '进行中',
    'completed': '已完成',
    'canceled': '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 获取任务状态对应的标签类型
const getStatusTag = (status) => {
  const tagMap = {
    'pending': '',
    'in_progress': 'warning',
    'completed': 'success',
    'canceled': 'info'
  };
  return tagMap[status] || '';
};

onMounted(() => {
  fetchTasks();
});
</script>

<style scoped>
.task-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.task-card {
  margin-bottom: 0;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  font-weight: bold;
  font-size: 16px;
}

.task-reward {
  font-weight: bold;
  color: #f56c6c;
  font-size: 18px;
}

.task-content {
  margin-bottom: 15px;
}

.task-description {
  margin-bottom: 10px;
  color: #606266;
  line-height: 1.5;
}

.task-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.task-actions {
  display: flex;
  gap: 10px;
}

/* 任务详情对话框样式 */
.task-detail-dialog {
  padding: 0 20px;
}

.detail-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #303133;
}

.detail-item {
  margin-bottom: 8px;
  display: flex;
}

.item-label {
  width: 80px;
  color: #909399;
}

.item-value {
  flex: 1;
  color: #303133;
}
</style>